<?php

App::uses('AppModel', 'Model');
class Contract extends AppModel{
    public $name = 'Contract';
    
    public $validate = array(
        'title' => array(
            'nonEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => 'A Title is required',
                'allowEmpty' => false,
            ),
            'unique' => array(
                'rule'    => array('isUniqueTitle'),
                'message' => ' This Title is already in use'
            )
        ),
        'path' => array(
            'rule' => 'checkFilesExtension', // or: array('ruleName', 'param1', 'param2' ...)
            'required' => true,
            'allowEmpty' => false,
            'on' => 'create', // or: 'update'
            'last' => false,
            'message' => 'Field Required'
        )
    );
    
    /**
     * Before isUniqueTitle
     * @param array $options
     * @return boolean
     */
    function isUniqueTitle($check) {
        $title = $this->find('first', array(
            'fields' => array(
                'Contract.id',
                'Contract.title'
            ),
            'conditions' => array(
                'Contract.title' => $check['title'],
                'Contract.batch_list_id' => $this->data['Contract']['batch_list_id']
            ))
        );

        if (!empty($title)) {
            if (isset($this->data[$this->alias]['id'])) {
                if ($this->data[$this->alias]['id'] == $title['Contract']['id']) {
                    return true;
                } else {
                    return false;
                }
            }
        } else {
            return true;
        }
    }
    
    /**
     * Before checkFilesExtension
     * @param array $options
     * @return boolean
     */
    public function checkFilesExtension($data){
        if ($data['path']) {
            $pathInfo = pathinfo($data['path']);
            if (in_array($pathInfo['extension'], array('pdf'))) {
                return true;
            } else {
                return FALSE;
            }
        }
    }
}

